<?php
/**
 * APP充值
 * Created by PhpStorm.
 * User: liJia
 * Date: 2020/4/16
 * Time: 18:33
 */

namespace app\api\controller;

use think\facade\Db;


class Apppay extends Common
{
    // 支付宝
    public $aliConfig;
    public $notify_url;

    // 微信
    public $wxConfig;
    public function __construct()
    {
        date_default_timezone_set('Asia/Shanghai');
        parent::__construct();
        // 支付宝
        $this->aliConfig = config('pay.Payment');
        $this->aliConfig['use_sandbox'] = true;
        $this->aliConfig['notify_url'] = $this->url . '/api/Apppay/paynotify';
        $this->aliConfig['return_url'] = $this->url . '/#/paysuccess';
        $this->aliConfig['limit_pay'] = [];
        $this->aliConfig['fee_type'] = "CNY";
        $this->aliConfig['app_id'] = '2021001185639187';
        $this->aliConfig['sign_type'] = 'RSA2';
        // 微信
        $this->wxConfig = config('pay.WeChat');
        $this->wxConfig['app_cert_pem'] = BASE_PATH . 'wx' . DIRECTORY_SEPARATOR . 'pem' . DIRECTORY_SEPARATOR . 'apiclient_cert.pem';
        $this->wxConfig['app_key_pem'] = BASE_PATH . 'wx' . DIRECTORY_SEPARATOR . 'pem' . DIRECTORY_SEPARATOR . 'apiclient_key.pem';
        $this->wxConfig['notify_url'] = $this->url . '/api/Apppay/notify';
    }


    /**
     * 支付宝支付入口，获取支付参数
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payByPayment()
    {
        $recharge_id = input('param.recharge_id', 0, 'intval');
        if (!$recharge_id){
            return resJson(0, '请传入充值id', '');
        }
        $orders = Db::name('recharge')->where(array('id' => $recharge_id))->find();
        if ($orders['status'] != 0) {
            return resJson(0, '订单类型不需要支付', '');
        }
        $payData = [
            'body'         => '充值',
            'subject'      => '充值',
            'trade_no'     => $orders['id'],
            'time_expire'  => time() + 600, // 表示必须 600s 内付款
            'amount'       => $orders['money'], // 单位为元 ,最小为0.01
            'return_param' => 'recharge',
            'goods_type' => '0',
            'store_id'   => ''
        ];
        try {
            $client = new \Payment\Client(\Payment\Client::ALIPAY, $this->aliConfig);
            $res    = $client->pay(\Payment\Client::ALI_CHANNEL_APP, $payData);
            return resJson(200, '', ['config' => $res]);
        } catch (\InvalidArgumentException $e) {
            return resJson(1033, $e->getMessage(), '');
        } catch (\Payment\Exceptions\GatewayException $e) {
            return resJson(1033, $e->getMessage(), '');
        } catch (\Payment\Exceptions\ClassNotFoundException $e) {
            return resJson(1033, $e->getMessage(), '');
        } catch (\Exception $e) {
            return resJson(1033, $e->getMessage(), '');
        }
    }

    /**
     * APP微信支付入口
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payByWeChat(){
        define('MAGIC_QUOTES_GPC',ini_set("magic_quotes_runtime",0)?True:False);
        $wxConfig = $this->wxConfig;
        $recharge_id = input('param.recharge_id', 0, 'intval');
        if (!$recharge_id){
            return resJson(0, '请传入充值id', '');
        }
        $orders = Db::name('recharge')->where(array('id' => $recharge_id))->find();
        if ($orders['status'] != 0) {
            return resJson(0, '订单类型不需要支付', '');
        }
        // 订单信息
        $payData = [
            'body'         => '充值',
            'subject'      => '充值',
            'trade_no'     => $orders['id'],
            'time_expire'  => time() + 600, // 表示必须 600s 内付款
            'amount'       => $orders['money'],
            'return_param' => $orders['id'],
            'client_ip'    => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1', // 客户地址
        ];
        try {
            $client = new \Payment\Client(\Payment\Client::WECHAT, $wxConfig);
            $res    = $client->pay(\Payment\Client::WX_CHANNEL_APP, $payData);
            return resJson(200, '', ['config' => $res]);
        } catch (\InvalidArgumentException $e) {
            return resJson(0, $e->getMessage(), '1');
        } catch (\Payment\Exceptions\GatewayException $e) {
            return resJson(0, $e->getMessage(), '2');
        } catch (\Payment\Exceptions\ClassNotFoundException $e) {
            return resJson(0, $e->getMessage(), '3');
        } catch (\Exception $e) {
            return resJson(0, $e->getMessage(), '4');
        }
    }

    /**
     * 支付宝回调
     */
    public function paynotify()
    {
        $config = $this->aliConfig;
        $proxy = \Payment\Client::ALIPAY;
        $callback = new RechargeNotify();
        try {
            $client = new \Payment\Client($proxy, $config);
            $xml    = $client->notify($callback);
        } catch (\InvalidArgumentException $e) {
            $this->fileinput($e->getMessage());
        } catch (\Payment\Exceptions\GatewayException $e) {
            $this->fileinput($e->getMessage());
        } catch (\Payment\Exceptions\ClassNotFoundException $e) {
            $this->fileinput($e->getMessage());
        } catch (\Exception $e) {
            $this->fileinput($e->getMessage());
        }
    }


    /**
     * 微信回调
     */
    public function notify(){
        $wxConfig = $this->wxConfig;
        $proxy  = \Payment\Client::WECHAT;
        $callback = new RechargeNotify();
        try {
            $client = new \Payment\Client($proxy, $wxConfig);
            $xml    = $client->notify($callback);
        } catch (\InvalidArgumentException $e) {
            $this->fileinput($e->getMessage());
        } catch (\Payment\Exceptions\GatewayException $e) {
            $this->fileinput($e->getMessage());
        } catch (\Payment\Exceptions\ClassNotFoundException $e) {
            $this->fileinput($e->getMessage());
        } catch (\Exception $e) {
            $this->fileinput($e->getMessage());
        }
    }

    public function fileinput($str='测试数据:')
    {
        $date = date('Y-m-d H:i:s');
        $content = "alipay执行日期notify：".$date."\n".$str."\n\n";
        file_put_contents('paydata.log', $content);
    }
}